package 搜索算法.广度优先搜索;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 1. 问题描述
 *
 * 2. 算法分析
 *
 * 3. 代码实现
 */

class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};


@SuppressWarnings("all")
public class N叉树的最大深度 {
    public static void main(String[] args) {

    }

    // 队列+递归   效率比较低
    public static int maxDepth1(Node root) {
        if(root == null) {
            return 0;
        }
        int max = 1;
        Deque<Node> deque = new LinkedList<>();
        List<Node> childlist = root.children;
        for(Node node : childlist) {
            deque.offer(node);
            max = Math.max(max,maxDepth1(node) + 1);
        }
        return max;
    }

    // 递归 优化版
    public int maxDepth2(Node root) {
        if(root == null) {return 0;}
        int max = 1;
        for(Node node : root.children) {
            max = Math.max(max,maxDepth2(node)+1);
        }
        return max;
    }

    // 非递归实现
    public static int maxDepth(Node root) {
        if(root == null) {return 0;}
        int level = 0; // 记录N叉树的层数
        Deque<Node> deque = new LinkedList<>();
        deque.offer(root);
        while(!deque.isEmpty()) {
            int sum = deque.size(); // 获取当前层的所有节点数量
            while(sum > 0) {
                Node cur = deque.poll();
                for(Node node : cur.children) {
                    deque.offer(node);
                }
                sum--;
            }
            level++;
        }
        return level;
    }
}
